04. Defining a Class

title

Defining a Class

ND079 JAVA C1 L2 A06 Defining A Class

Parts of a Class Definition

Classes are composed of the following different parts:

  • The class name, which is always formatted in UpperCamelCase.
  • The class variables, which can be either primitives or object references. Note that you'll want to mark these private to protect your instance variables so other classes do not have direct access to them.
  • The constructor which is a special method used to initialize the object when it is created.
  • The methods used to define the behavior that objects of the class will share.
    • Accessor methods provide access to instance variables. The names of accessor methods typically start with "get".
    • Mutator methods allow other objects to change the values. The names of mutator methods start with "set".

Instance Variables vs Class Variables

Note the difference between instance variables and class variables.

  • Instance Variables are state variables that can have unique values for each object.
  • Class Variables are state variables that belong to the class itself, and are the same for every object. The static keyword identifies this variable as belonging to the class (not to individual objects).

Example

For your reference, here's the example code we looked at in the video:

public class Student {

  private final String id;
  private final String firstName;
  private final String lastName;

  public Student(String id, String firstName,String lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getId(){
    return id;
  }

  public String getFirstName(){
    return lastName;
  }

  public String getLastName(){
    return lastName;
  }
}

QUIZ QUESTION::

Below are the different parts of a class we just discussed. Can you match each part with the correct description?

ANSWER CHOICES:



Description

Part of the class

A type of function used to model the behavior of the class.

Used to initialize objects during instantiation.

Used to provide state for the objects.

Used to identify not only the class itself, but also the associated Java file.

SOLUTION:

Description

Part of the class

Used to initialize objects during instantiation.

A type of function used to model the behavior of the class.

Used to identify not only the class itself, but also the associated Java file.

Used to provide state for the objects.